3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\MediaWikiServices
;
22 use Wikimedia\Rdbms\DBReplicationWaitError
;
25 * Job for pruning recent changes
30 class RecentChangesUpdateJob
extends Job
{
31 function __construct( Title
$title, array $params ) {
32 parent
::__construct( 'recentChangesUpdate', $title, $params );
34 if ( !isset( $params['type'] ) ) {
35 throw new Exception( "Missing 'type' parameter." );
38 $this->executionFlags |
= self
::JOB_NO_EXPLICIT_TRX_ROUND
;
39 $this->removeDuplicates
= true;
43 * @return RecentChangesUpdateJob
45 final public static function newPurgeJob() {
47 SpecialPage
::getTitleFor( 'Recentchanges' ), [ 'type' => 'purge' ]
52 * @return RecentChangesUpdateJob
55 final public static function newCacheUpdateJob() {
57 SpecialPage
::getTitleFor( 'Recentchanges' ), [ 'type' => 'cacheUpdate' ]
61 public function run() {
62 if ( $this->params
['type'] === 'purge' ) {
63 $this->purgeExpiredRows();
64 } elseif ( $this->params
['type'] === 'cacheUpdate' ) {
65 $this->updateActiveUsers();
67 throw new InvalidArgumentException(
68 "Invalid 'type' parameter '{$this->params['type']}'." );
74 protected function purgeExpiredRows() {
75 global $wgRCMaxAge, $wgUpdateRowsPerQuery;
77 $lockKey = wfWikiID() . ':recentchanges-prune';
79 $dbw = wfGetDB( DB_MASTER
);
80 if ( !$dbw->lock( $lockKey, __METHOD__
, 0 ) ) {
81 // already in progress
85 $factory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
86 $ticket = $factory->getEmptyTransactionTicket( __METHOD__
);
87 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
88 $rcQuery = RecentChange
::getQueryInfo();
95 [ 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ],
97 [ 'LIMIT' => $wgUpdateRowsPerQuery ],
100 foreach ( $res as $row ) {
101 $rcIds[] = $row->rc_id
;
105 $dbw->delete( 'recentchanges', [ 'rc_id' => $rcIds ], __METHOD__
);
106 Hooks
::run( 'RecentChangesPurgeRows', [ $rows ] );
107 // There might be more, so try waiting for replica DBs
109 $factory->commitAndWaitForReplication(
110 __METHOD__
, $ticket, [ 'timeout' => 3 ]
112 } catch ( DBReplicationWaitError
$e ) {
113 // Another job will continue anyway
119 $dbw->unlock( $lockKey, __METHOD__
);
122 protected function updateActiveUsers() {
123 global $wgActiveUserDays;
125 // Users that made edits at least this many days ago are "active"
126 $days = $wgActiveUserDays;
127 // Pull in the full window of active users in this update
128 $window = $wgActiveUserDays * 86400;
130 $dbw = wfGetDB( DB_MASTER
);
131 $factory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
132 $ticket = $factory->getEmptyTransactionTicket( __METHOD__
);
134 $lockKey = wfWikiID() . '-activeusers';
135 if ( !$dbw->lock( $lockKey, __METHOD__
, 0 ) ) {
136 // Exclusive update (avoids duplicate entries)… it's usually fine to just
137 // drop out here, if the Job is already running.
141 // Long-running queries expected
142 $dbw->setSessionOptions( [ 'connTimeout' => 900 ] );
145 // Get the last-updated timestamp for the cache
146 $cTime = $dbw->selectField( 'querycache_info',
148 [ 'qci_type' => 'activeusers' ]
150 $cTimeUnix = $cTime ?
wfTimestamp( TS_UNIX
, $cTime ) : 1;
152 // Pick the date range to fetch from. This is normally from the last
153 // update to till the present time, but has a limited window for sanity.
154 // If the window is limited, multiple runs are need to fully populate it.
155 $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
156 $eTimestamp = min( $sTimestamp +
$window, $nowUnix );
158 // Get all the users active since the last update
159 $actorQuery = ActorMigration
::newMigration()->getJoin( 'rc_user' );
161 [ 'recentchanges' ] +
$actorQuery['tables'],
163 'rc_user_text' => $actorQuery['fields']['rc_user_text'],
164 'lastedittime' => 'MAX(rc_timestamp)'
167 $actorQuery['fields']['rc_user'] . ' > 0', // actual accounts
168 'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL
), // no wikidata
169 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
170 'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
171 'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
175 'GROUP BY' => [ 'rc_user_text' ],
176 'ORDER BY' => 'NULL' // avoid filesort
181 foreach ( $res as $row ) {
182 $names[$row->rc_user_text
] = $row->lastedittime
;
185 // Find which of the recently active users are already accounted for
186 if ( count( $names ) ) {
187 $res = $dbw->select( 'querycachetwo',
188 [ 'user_name' => 'qcc_title' ],
190 'qcc_type' => 'activeusers',
191 'qcc_namespace' => NS_USER
,
192 'qcc_title' => array_keys( $names ),
193 'qcc_value >= ' . $dbw->addQuotes( $nowUnix - $days * 86400 ), // TS_UNIX
197 // Note: In order for this to be actually consistent, we would need
198 // to update these rows with the new lastedittime.
199 foreach ( $res as $row ) {
200 unset( $names[$row->user_name
] );
204 // Insert the users that need to be added to the list
205 if ( count( $names ) ) {
207 foreach ( $names as $name => $lastEditTime ) {
209 'qcc_type' => 'activeusers',
210 'qcc_namespace' => NS_USER
,
211 'qcc_title' => $name,
212 'qcc_value' => wfTimestamp( TS_UNIX
, $lastEditTime ),
213 'qcc_namespacetwo' => 0, // unused
214 'qcc_titletwo' => '' // unused
217 foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
218 $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__
);
219 $factory->commitAndWaitForReplication( __METHOD__
, $ticket );
223 // If a transaction was already started, it might have an old
224 // snapshot, so kludge the timestamp range back as needed.
225 $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
227 // Touch the data freshness timestamp
228 $dbw->replace( 'querycache_info',
230 [ 'qci_type' => 'activeusers',
231 'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ], // not always $now
235 $dbw->unlock( $lockKey, __METHOD__
);
237 // Rotate out users that have not edited in too long (according to old data set)
238 $dbw->delete( 'querycachetwo',
240 'qcc_type' => 'activeusers',
241 'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX